//
//  UICityPicker.m
//  DDMates
//
//  Created by ShawnMa on 12/16/11.
//  Copyright (c) 2011 TelenavSoftware, Inc. All rights reserved.
//

#import "TSLocateView.h"
#import "Util.h"

#define kDuration 0.3

@interface TSLocateView ()

@property (nonatomic, retain) UIView *maskView;

@end

@implementation TSLocateView

@synthesize locatePicker;
@synthesize locate;
@synthesize maskView;

- (void)dealloc
{
	SAFE_RELEASE(locatePicker);
	SAFE_RELEASE(locate);
	SAFE_RELEASE(provinces);
	SAFE_RELEASE(maskView);
	
	[super dealloc];
}

- (void)_initWithPostCode:(NSString *)postCode delegate:(id /*<UIActionSheetDelegate>*/)delegate
{
	self.delegate = delegate;
	
	//加载数据
	provinces = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ProvincesAndCities.plist" ofType:nil]];
	
	NSUInteger provinceIndex = 0;
	NSUInteger cityIndex = 0;
	
	if ([postCode length])
	{
		for (NSUInteger i=0; i<[provinces count] && provinceIndex == 0; i++)
		{
			NSDictionary *province = [provinces objectAtIndex:i];
			cities = [province objectForKey:@"Cities"];
			for (NSUInteger j=0; j<[cities count]; j++)
			{
				NSDictionary *city = [cities objectAtIndex:j];
				if ([[city objectForKey:@"postcode"] isEqualToString:postCode])
				{
					provinceIndex = i;
					cityIndex = j;
					break;
				}
			}
		}
	}
	
	cities = [[provinces objectAtIndex:provinceIndex] objectForKey:@"Cities"];
	
	//初始化默认数据
	self.locate = [[[TSLocation alloc] init] autorelease];
	self.locate.state = [[provinces objectAtIndex:provinceIndex] objectForKey:@"State"];
	self.locate.city = [[cities objectAtIndex:cityIndex] objectForKey:@"city"];
	self.locate.postcode = postCode;
	self.locate.latitude = [[[cities objectAtIndex:cityIndex] objectForKey:@"lat"] doubleValue];
	self.locate.longitude = [[[cities objectAtIndex:cityIndex] objectForKey:@"lon"] doubleValue];
	
	[self.locatePicker selectRow:provinceIndex inComponent:0 animated:NO];
	[self.locatePicker selectRow:cityIndex inComponent:1 animated:NO];
}

- (id)initWithPostCode:(NSString *)postCode delegate:(id /*<UIActionSheetDelegate>*/)delegate
{
	NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"TSLocateView"
                                                          owner:nil
                                                        options:nil];
    
    if ([arrayOfViews count] < 1){
        [self release];
        return nil;
    }
    
    TSLocateView *newView = [[arrayOfViews objectAtIndex:0] retain];
    
    [self release];
    self = newView;

    if (self)
	{		
        [self _initWithPostCode:postCode delegate:delegate];
    }
    return self;
}

- (void)showInView:(UIView *) view
{
    CATransition *animation = [CATransition  animation];
    animation.duration = kDuration;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromTop;
    [self setAlpha:1.0f];
    [self.layer addAnimation:animation forKey:nil];
	
	self.layer.shadowOffset = CGSizeMake(0, 0);
    self.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.layer.shadowOpacity = 0.8;

	UIView *mainView = [Util rootViewController].view;
    
    self.frame = CGRectMake(0, mainView.frame.size.height - self.frame.size.height, self.frame.size.width, self.frame.size.height);
	
	self.maskView = [[[UIView alloc] initWithFrame:mainView.bounds] autorelease];
	self.maskView.backgroundColor = [UIColor blackColor];
	self.maskView.alpha = 0.2;

	animation = [CATransition animation];
	animation.duration = kDuration;
	animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionReveal;
	[self.maskView.layer addAnimation:animation forKey:nil];
	
	[mainView addSubview:self.maskView];
	
    [mainView addSubview:self];
}

#pragma mark - PickerView lifecycle

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return [provinces count];
            break;
        case 1:
            return [cities count];
            break;
        default:
            return 0;
            break;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return [[provinces objectAtIndex:row] objectForKey:@"State"];
            break;
        case 1:
            return [[cities objectAtIndex:row] objectForKey:@"city"];
            break;
        default:
            return nil;
            break;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    switch (component) {
        case 0:
            cities = [[provinces objectAtIndex:row] objectForKey:@"Cities"];
            [self.locatePicker selectRow:0 inComponent:1 animated:NO];
            [self.locatePicker reloadComponent:1];
            
            self.locate.state = [[provinces objectAtIndex:row] objectForKey:@"State"];
            self.locate.city = [[cities objectAtIndex:0] objectForKey:@"city"];
			self.locate.postcode = [[cities objectAtIndex:0] objectForKey:@"postcode"];
            self.locate.latitude = [[[cities objectAtIndex:0] objectForKey:@"lat"] doubleValue];
            self.locate.longitude = [[[cities objectAtIndex:0] objectForKey:@"lon"] doubleValue];
            break;
        case 1:
            self.locate.city = [[cities objectAtIndex:row] objectForKey:@"city"];
			self.locate.postcode = [[cities objectAtIndex:row] objectForKey:@"postcode"];
            self.locate.latitude = [[[cities objectAtIndex:row] objectForKey:@"lat"] doubleValue];
            self.locate.longitude = [[[cities objectAtIndex:row] objectForKey:@"lon"] doubleValue];
            break;
        default:
            break;
    }
}


#pragma mark - Button lifecycle

- (void)viewsRemoveFromSuperview
{
	[self removeFromSuperview];
	[self.maskView removeFromSuperview];
	
//	SAFE_RELEASE(provinces);
//	SAFE_RELEASE(maskView);
}

- (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated
{
	if (animated)
	{
		CATransition *animation = [CATransition  animation];
		animation.duration = kDuration;
		animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
		animation.type = kCATransitionPush;
		animation.subtype = kCATransitionFromBottom;
		[self setAlpha:0.0f];
		[self.layer addAnimation:animation forKey:nil];
		
		animation = [CATransition animation];
		animation.duration = kDuration;
		animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
		animation.type = kCATransitionFade;
		[self.maskView.layer addAnimation:animation forKey:nil];

		[self performSelector:@selector(viewsRemoveFromSuperview) withObject:nil afterDelay:kDuration];
	}
	else
	{
		[self viewsRemoveFromSuperview];
	}
	
	if (self.delegate && [self.delegate respondsToSelector:@selector(actionSheet:clickedButtonAtIndex:)])
	{
        [self.delegate actionSheet:self clickedButtonAtIndex:buttonIndex];
    }
}

- (IBAction)cancel:(id)sender {
    [self dismissWithClickedButtonIndex:0 animated:YES];
}

- (IBAction)locate:(id)sender {
    [self dismissWithClickedButtonIndex:1 animated:YES];
}

@end
